package com.zhentao.controller;

import com.zhentao.pojo.Order;
import com.zhentao.pojo.Product;
import com.zhentao.pojo.UserCollection;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author gyz
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    UserService userService;
    @Autowired
    UserCollectionService userCollectionService;
    //获取所以产品
    @RequestMapping("productAll")
    public Object getProductAll(){
        List<Product> list = productService.list();
        List<Product> list1 = new ArrayList<>();
        for (Product product : list) {
            // product.setCategory(categoryService.getById(product.getCategoryId())); // 注释掉，因为setter方法不存在
            list1.add(product);
        }
        return  list1;
    }
    //产品详情
    @RequestMapping("productById")
    public Object getProductById(Integer id){
        return productService.getById(id);
    }
    //获取登录用户的订单
    @RequestMapping("OrderByUserId")
    public Object getOrderByUserId(Long userId){
        List<Order> list = orderService.list();
        List<Order> list1 = new ArrayList<>();
        for (Order order : list) {
            if(order.getUserId()==userId){
                order.setProduct(productService.getById(Long.valueOf(order.getProductid())));
                list1.add(order);
            }
        }
        return list1;
    }
    //产品下单功能
    @RequestMapping("OrderAdd")
    public Object OrderAdd(@RequestBody Order order){
        orderService.save(order);
        return "下单成功";
    }
    //查看订单详情
    @RequestMapping("OrderById")
    public Object OrderAdd(Long id){
        Order byId = orderService.getById(id);
        byId.setProduct(productService.getById(Long.valueOf(byId.getProductid())));
        byId.setUser(userService.getById(byId.getUserId()));
        return byId;
    }
    //取消订单
    //查看订单详情
    @RequestMapping("OrderQuxiao")
    public Object OrderQuxiao(Long id){
        Order byId = orderService.getById(id);
        byId.setStatus(3);
        orderService.updateById(byId);
        return "订单已取消";
    }

    //根据用户收藏推荐产品
    @RequestMapping("getRecommendations")
    public Object getRecommendations(Long userId, Integer limit){
        try {
            if (userId == null) {
                return new ArrayList<>();
            }
            
            // 设置默认推荐数量
            if (limit == null || limit <= 0) {
                limit = 6;
            }
            
            // 获取用户收藏的商品
            List<UserCollection> collections = userCollectionService.list(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCollection>()
                    .eq("user_id", userId)
                    .eq("entity_type", "product")
            );
            
            if (collections.isEmpty()) {
                // 如果用户没有收藏商品，返回热门商品
                return getHotProducts(limit);
            }
            
            // 提取收藏商品的分类ID
            Set<Long> collectedCategoryIds = new HashSet<>();
            Set<Long> collectedProductIds = new HashSet<>();
            
            for (UserCollection collection : collections) {
                collectedProductIds.add(collection.getEntityId());
                Product product = productService.getById(collection.getEntityId());
                if (product != null && product.getCategoryId() != null) {
                    collectedCategoryIds.add(Long.valueOf(product.getCategoryId()));
                }
            }
            
            if (collectedCategoryIds.isEmpty()) {
                return getHotProducts(limit);
            }
            
            // 查找同分类的其他商品（排除已收藏的）
            List<Product> recommendedProducts = new ArrayList<>();
            
            for (Long categoryId : collectedCategoryIds) {
                List<Product> categoryProducts = productService.list(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Product>()
                        .eq("category_id", categoryId)
                        .notIn("id", collectedProductIds)
                        .orderByDesc("sales") // 按销量排序
                        .last("LIMIT " + limit)
                );
                recommendedProducts.addAll(categoryProducts);
            }
            
            // 如果推荐商品不足，补充热门商品
            if (recommendedProducts.size() < limit) {
                List<Product> hotProducts = getHotProducts(limit - recommendedProducts.size());
                recommendedProducts.addAll(hotProducts);
            }
            
            // 去重并限制数量
            Set<Long> addedIds = new HashSet<>();
            List<Product> finalRecommendations = new ArrayList<>();
            
            for (Product product : recommendedProducts) {
                if (!addedIds.contains(product.getId()) && finalRecommendations.size() < limit) {
                    addedIds.add(product.getId());
                    finalRecommendations.add(product);
                }
            }
            
            return finalRecommendations;
            
        } catch (Exception e) {
            System.err.println("获取推荐产品失败: " + e.getMessage());
            e.printStackTrace();
            return getHotProducts(limit != null ? limit : 6);
        }
    }
    
    // 获取热门商品
    private List<Product> getHotProducts(int limit) {
        try {
            return productService.list(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Product>()
                    .orderByDesc("sales")
                    .last("LIMIT " + limit)
            );
        } catch (Exception e) {
            System.err.println("获取热门商品失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    // AI对话推荐产品
    @RequestMapping("aiRecommend")
    public Object aiRecommend(@RequestParam String query, @RequestParam(required = false) Long userId) {
        try {
            System.out.println("AI推荐请求: " + query + ", 用户ID: " + userId);
            
            // 解析用户需求
            String[] keywords = parseUserQuery(query);
            System.out.println("解析关键词: " + String.join(", ", keywords));
            
            // 根据关键词搜索产品
            List<Product> recommendedProducts = searchProductsByKeywords(keywords);
            
            // 生成AI回复
            String aiResponse = generateAiResponse(query, recommendedProducts);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "推荐成功");
            result.put("aiResponse", aiResponse);
            result.put("products", recommendedProducts);
            result.put("query", query);
            result.put("keywords", keywords);
            
            return result;
            
        } catch (Exception e) {
            System.err.println("AI推荐异常: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "AI推荐失败: " + e.getMessage());
            result.put("aiResponse", "抱歉，我暂时无法为您推荐产品，请稍后再试。");
            result.put("products", new ArrayList<>());
            return result;
        }
    }
    
    // 解析用户查询
    private String[] parseUserQuery(String query) {
        // 简单的关键词提取逻辑
        String[] commonKeywords = {
            "按摩", "按摩仪", "按摩枕", "按摩锤", "按摩器",
            "艾灸", "艾灸盒", "足浴", "足浴包", "泡脚",
            "枸杞", "黄芪", "中药", "养生", "保健",
            "颈椎", "腰椎", "肩膀", "背部", "腿部",
            "疼痛", "疲劳", "放松", "舒缓", "治疗",
            "电动", "手动", "便携", "家用", "办公"
        };
        
        List<String> foundKeywords = new ArrayList<>();
        String lowerQuery = query.toLowerCase();
        
        for (String keyword : commonKeywords) {
            if (lowerQuery.contains(keyword.toLowerCase())) {
                foundKeywords.add(keyword);
            }
        }
        
        // 如果没有找到关键词，使用原始查询
        if (foundKeywords.isEmpty()) {
            foundKeywords.add(query);
        }
        
        return foundKeywords.toArray(new String[0]);
    }
    
    // 根据关键词搜索产品
    private List<Product> searchProductsByKeywords(String[] keywords) {
        try {
            List<Product> allProducts = productService.list();
            List<Product> matchedProducts = new ArrayList<>();
            
            for (Product product : allProducts) {
                boolean isMatch = false;
                String productText = (product.getName() + " " + 
                    (product.getIntro() != null ? product.getIntro() : "") + " " + 
                    (product.getDetail() != null ? product.getDetail() : "")).toLowerCase();
                
                for (String keyword : keywords) {
                    if (productText.contains(keyword.toLowerCase())) {
                        isMatch = true;
                        break;
                    }
                }
                
                if (isMatch) {
                    matchedProducts.add(product);
                }
            }
            
            // 按销量排序，限制返回数量
            matchedProducts.sort((a, b) -> Integer.compare(
                b.getSales() != null ? b.getSales() : 0,
                a.getSales() != null ? a.getSales() : 0
            ));
            
            return matchedProducts.size() > 6 ? matchedProducts.subList(0, 6) : matchedProducts;
            
        } catch (Exception e) {
            System.err.println("搜索产品失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    
    // 生成AI回复
    private String generateAiResponse(String query, List<Product> products) {
        if (products.isEmpty()) {
            return "抱歉，我没有找到符合您要求的产品。您可以尝试其他关键词，比如'按摩'、'艾灸'、'养生'等。";
        }
        
        StringBuilder response = new StringBuilder();
        response.append("根据您的需求「").append(query).append("」，我为您推荐以下产品：\n\n");
        
        for (int i = 0; i < Math.min(products.size(), 3); i++) {
            Product product = products.get(i);
            response.append("• ").append(product.getName())
                   .append(" - ¥").append(product.getPrice());
            if (product.getOriginalPrice() != null && product.getOriginalPrice() > product.getPrice()) {
                response.append(" (原价¥").append(product.getOriginalPrice()).append(")");
            }
            response.append("\n");
        }
        
        if (products.size() > 3) {
            response.append("\n还有").append(products.size() - 3).append("款相关产品，您可以查看更多。");
        }
        
        response.append("\n这些产品都经过精心挑选，希望能满足您的需求！");
        
        return response.toString();
    }


}
